var conId=null;//会诊ID
var oprType=null;//操作类型
var status=null;//会诊状态
var isBack=null;//是否退回
var alreadyUploadAttachMent=false;//是否已经上传附件

var transItemCodeMap = {
	con_class : getTransParam('conClasseInfo'),
	con_type : getTransParam('conTypeInfo'),
	sex : getTransParam('sexInfo'),
	ageunit : getTransParam('ageunitInfo'),
	expect_type:getTransParam('expectType'),
	emergency:getTransParam('emergencyType'),
	nationality:getTransParam('nationalityCode'),
	marital_status:getTransParam('marryType'),
	medical_type:getTransParam('medicalType'),
	nation:getTransParam('nationCode'),
	visiting_type:getTransParam('visitingType')
};

(function() {
	//通用设置
	commonSet();
	//初始化详情页
	initDetail();
	//事件绑定
	eventBind();
})();

//通用设置
function commonSet(){
	initLoader();
	initDatePickers();
	conId=$("#conId").val();
	oprType=$("#type").val();
	status=$("#status").val();
	isBack=$("#isBack").val();
}

//初始化详情页
function initDetail(){
	switch(oprType){
		case 'myApply'://我的申请
			//绑定会诊信息
			getConsultationInfo().then(function(data){
				if(isBack=='1'){
					initBackInfo(data.payload.consultationInfo);
					initTimeLine(data.payload.timeline);//显示时间轴
				}
				if(status=='10'){
					initConInfoForm(data.payload.consultationInfo);
					initPatientInfoForm(data.payload.patientInfo);
					initClinicInfoForm(data.payload.patientInfo,data.payload.attachmentlist);
				}else{
					initConInfoTable(data.payload.vconsultationInfo);
					initTimeLine(data.payload.timeline);//显示时间轴
					initPatientInfoTable(data.payload.patientInfo);
					initClinicInfoTable(data.payload.patientInfo,data.payload.attachmentlist);
					if(status=='40'||status=='50'||status=='60'){
						initAssignInfoTable(data.payload.assignInfo[0]);
						if(status=='60'){
							//会诊完成显示费用
							initCostInfo(data.payload.assignInfo[0].allot_docid);
						}
					}
					if(status=='50'||status=='60'){
						initReportInfoTable(data.payload.reportInfo[0]);
					}
				}
			});
		break;
		case 'qcBefore'://前质控
			//绑定会诊信息
			getConsultationInfo().then(function(data){
				if(isBack=='1'){
					initBackInfo(data.payload.consultationInfo);
					initTimeLine(data.payload.timeline);//显示时间轴
				}
				initConInfoTable(data.payload.vconsultationInfo);
				initTimeLine(data.payload.timeline);//显示时间轴
				initPatientInfoTable(data.payload.patientInfo);
				initClinicInfoTable(data.payload.patientInfo,data.payload.attachmentlist);
			});
		break;
		case 'assign'://分诊
			//绑定会诊信息
			getConsultationInfo().then(function(data){
				if(isBack=='1'){
					initBackInfo(data.payload.consultationInfo);
					initTimeLine(data.payload.timeline);//显示时间轴
				}
				initConInfoTable(data.payload.vconsultationInfo);
				initTimeLine(data.payload.timeline);//显示时间轴
				initPatientInfoTable(data.payload.patientInfo);
				initClinicInfoTable(data.payload.patientInfo,data.payload.attachmentlist);
				if(status=='30'){
					//初始化分诊表单项
					if(isBack=='1'){
						initAssignInfoForm(null,data.payload.assignInfo[0]);
					}else{
						initAssignInfoForm(data.payload.vconsultationInfo,null);
					}
				}else{
					initAssignInfoTable(data.payload.assignInfo[0]);
					if(status=='60'){
						//会诊完成显示费用
						initCostInfo(data.payload.assignInfo[0].allot_docid);
					}
				}
			});
		break;
		case 'myTask'://我的任务
			//绑定会诊信息
			getConsultationInfo().then(function(data){
				if(isBack=='1'){
					initBackInfo(data.payload.consultationInfo);
					initTimeLine(data.payload.timeline);//显示时间轴
				}
				initConInfoTable(data.payload.vconsultationInfo);
				initTimeLine(data.payload.timeline);//显示时间轴
				initPatientInfoTable(data.payload.patientInfo);
				initClinicInfoTable(data.payload.patientInfo,data.payload.attachmentlist);
				initAssignInfoTable(data.payload.assignInfo[0]);
				if(status=='60'){
					//会诊完成显示费用
					initCostInfo(data.payload.assignInfo[0].allot_docid);
				}
				if(status=='40'){
					//初始化报告表单项
					initReportInfoForm(data.payload.reportInfo[0]);
				}else{
					initReportInfoTable(data.payload.reportInfo[0]);
				}
			});
		break;
		case 'qcAfter'://后质控
			//绑定会诊信息
			getConsultationInfo().then(function(data){
				if(isBack=='1'){
					initBackInfo(data.payload.consultationInfo);
					initTimeLine(data.payload.timeline);//显示时间轴
				}
				initConInfoTable(data.payload.vconsultationInfo);
				initTimeLine(data.payload.timeline);//显示时间轴
				initPatientInfoTable(data.payload.patientInfo);
				initClinicInfoTable(data.payload.patientInfo,data.payload.attachmentlist);
				initAssignInfoTable(data.payload.assignInfo[0]);
				initReportInfoTable(data.payload.reportInfo[0]);
				if(status=='60'){
					//会诊完成显示费用
					initCostInfo(data.payload.assignInfo[0].allot_docid);
				}
			});
		break;
	}
}

//获得会诊信息
function getConsultationInfo(){
	var def = $.Deferred();
	$.getApiClient('/consultation/info/{conid}').setQuery({
		conid:conId
	}).get().done(function(data){
		def.resolve(data);
	});
	return def.promise();
}

//按钮事件绑定
function eventBind(){
	//返回按钮
	$("#returnBack").click(function(){
		redirectCallback();
	})
	
	//申请暂存
	$("#temporarySave").click(doTemporarySave);
	
	//取消申请
	$("#cancelApply").click(doCancelApply);
	
	//申请提交
	$("#commitApply").click(doCommitApply);
	
	//前质控通过
	$("#qcBeforeOk").click(doQcBeforeOk);
	
	//前质控退回
	$("#qcBeforeBack").click(function(){
		backDialog();
	})
	
	//分诊通过
	$("#assignaOk").click(doAssignOk);
	
	//分诊退回
	$("#assignBack").click(function(){
		backDialog();
	})
	
	//提交报告
	$("#reportOk").click(doReportOk);
	
	//报告退回
	$("#reportBack").click(function(){
		backDialog();
	})
	//加入会议
	$("#startConference").click(function(){
		startConference();
	})
	
	//后质控通过
	$("#qcAfterOk").click(doQcAfterOk);
	
	//后质控退回
	$("#qcAfterBack").click(function(){
		backDialog();
	})
}

//退回弹出层
function backDialog(){
	customRemoteUrlDialog('会诊退回','/page/business/consultation/common/conBack?type='+oprType, BootstrapDialog.SIZE_NORMAL);
}

//确认退回
function doBack(){
	switch(oprType){
		case 'qcBefore'://前质控
			doQcBeforeBack();
		break;
		case 'assign'://分诊
			doAssignBack();
		break;
		case 'myTask'://报告
			doReportBack();
		break;
		case 'qcAfter'://后质控
			doQcAfterBack();
		break;
	}
}

//申请暂存
function doTemporarySave(){
	if (!$("#conInfoForm").validationForm() || !$("#patientInfoForm").validationForm() || !$("#clinicInfoForm").validationForm()) {
		customAlertDialog("请填写必填项目后提交", '提示', null, null);
		return;
	}
	//其他校验
	var conType=$('#con_type').multipleSelect('getSelects')[0];
	if(conType=='1'){
		//点名
		if(!$('#assign_hos').multipleSelect('getSelects')[0]){
			customAlertDialog("指定医院需填写", '错误提示', null, null);
			return;
		}
		
		if(!$('#assign_dept').multipleSelect('getSelects')[0]){
			customAlertDialog("指定科室需填写", '错误提示', null, null);
			return;
		}
		
		if(!$('#assign_doc').multipleSelect('getSelects')[0]){
			customAlertDialog("指定医生需填写", '错误提示', null, null);
			return;
		}
	}else{
		if(!$('#assign_hos').multipleSelect('getSelects')[0]){
			customAlertDialog("指定医院需填写", '错误提示', null, null);
			return;
		}
		
		if(!$('#assign_dept').multipleSelect('getSelects')[0]){
			customAlertDialog("指定科室需填写", '错误提示', null, null);
			return;
		}
	}

	$.getApiClient('/consultation/save').post(collectApplyForm()).done(function(data) {
		if(data.code == "0"){
			var attachFile=$('#attachFrom input').get(0).files[0];
			if(attachFile){
				//附件上传
				uploadAttachment(conId,function(attachData){
					if(attachData.code == "0"){
						BootstrapDialog.closeAll();
						customTimeOutDialog('信息提示','保存成功,您可以稍后提交',null,2000);
						alreadyUploadAttachMent=true;
						//加载附件列表
						loadEditAttachTable(conId,null);
					}else{
						customAlertDialog(attachData.message, '错误提示', null, null);
					}
				})
			}else{
				BootstrapDialog.closeAll();
				customTimeOutDialog('信息提示','保存成功,您可以稍后提交',null,2000);
			}
		}else{
			customAlertDialog(data.message, '错误提示', null, null);
		}
	});
}

//提交申请
function doCommitApply() {
	if (!$("#conInfoForm").validationForm() || !$("#patientInfoForm").validationForm()||!$("#clinicInfoForm").validationForm()) {
		customAlertDialog("请填写必填项目后提交", '提示', null, null);
		return;
	}
	//其他校验
	var conType=$('#con_type').multipleSelect('getSelects')[0];
	if(conType=='1'){
		//点名
		if(!$('#assign_hos').multipleSelect('getSelects')[0]){
			customAlertDialog("指定医院需填写", '错误提示', null, null);
			return;
		}
		
		if(!$('#assign_dept').multipleSelect('getSelects')[0]){
			customAlertDialog("指定科室需填写", '错误提示', null, null);
			return;
		}
		
		if(!$('#assign_doc').multipleSelect('getSelects')[0]){
			customAlertDialog("指定医生需填写", '错误提示', null, null);
			return;
		}
	}else{
		if(!$('#assign_hos').multipleSelect('getSelects')[0]){
			customAlertDialog("指定医院需填写", '错误提示', null, null);
			return;
		}
		
		if(!$('#assign_dept').multipleSelect('getSelects')[0]){
			customAlertDialog("指定科室需填写", '错误提示', null, null);
			return;
		}
	}

	$.getApiClient('/consultation/apply').post(collectApplyForm()).done(function(data) {
		if(data.code == "0"){
			if(!alreadyUploadAttachMent){
				var attachFile=$('#attachFrom input').get(0).files[0];
				if(attachFile){
					//附件上传
					uploadAttachment(conId,function(attachData){
						if(attachData.code == "0"){
							customTimeOutDialog('信息提示','会诊申请提交成功',null,2000,function(){
								redirectCall('/page/business/consultation/list?type=myApply');
							});
						}else{
							customAlertDialog(attachData.message, '错误提示', null, null);
						}
					})
				}else{
					customTimeOutDialog('信息提示','会诊申请提交成功',null,2000,function(){
						redirectCall('/page/business/consultation/list?type=myApply');
					});
				}
			}else{
				customTimeOutDialog('信息提示','会诊申请提交成功',null,2000,function(){
					redirectCall('/page/business/consultation/list?type=myApply');
				});
			}
		}else{
			customAlertDialog(data.message, '错误提示', null, null);
		}
	});
}

//取消申请
function doCancelApply() {
	$.getApiClient('/consultation/cancelApply/{conid}').setQuery({
		conid:conId
	}).put().done(function(data){
		if(data.code == "0"){
			customTimeOutDialog('信息提示','操作成功',null,2000,function(){
				redirectCall('/page/business/consultation/list?type=myApply');
			});
		}else{
			customAlertDialog(data.message, '错误提示', null, null);
		}
	});
}

//收集表单数据
function collectApplyForm() {
	var applyFormData = {};
	//会诊信息表单数据
	var conForm = $('#conInfoForm').collect();
	//患者信息表单数据
	var patientForm = $('#patientInfoForm').collect();
	//临床信息表单数据
	var clinicForm = $('#clinicInfoForm').collect();
	//流程信息表单数据
	var processForm = $('#processInfoForm').collect();
	//扩展信息
	var extendInfo = {
		con_id:	conId || '',	
		patient_id:	$('#patient_id').val(),
		con_class : $('#con_class').val()// 会诊类型
	};
	$.extend(applyFormData, conForm, patientForm, clinicForm, processForm,extendInfo);
	console.log(applyFormData);
	return applyFormData;
}

//附件上传
function uploadAttachment(business_id,callback){
	var form = new FormData($("#attachFrom")[0]);
	$.ajax({
		url : path+'/api/attachment/upload/'+business_id,
		type : "post",
		data : form,
		processData : false,
		contentType : false,
		dataType : "json",
		success : function(data) {
			callback(data);
		}
	});
}

//前质控通过
function doQcBeforeOk(){
	$.getApiClient('/consultation/qcBefore/{conid}/done').setQuery({
		conid:conId
	}).put('#processInfoForm').done(function(data){
		if(data.code == "0"){
			customTimeOutDialog('信息提示','操作成功',null,2000,function(){
				redirectCall('/page/business/consultation/list?type=qcBefore');
			});
		}else{
			customAlertDialog(data.message, '错误提示', null, null);
		}
	});
}

//前质控退回
function doQcBeforeBack(){
	$.getApiClient('/consultation/qcBefore/{conid}/back').setQuery({
		conid:conId
	}).put('#backInfoForm',function(params){
		return $.extend(params,$('#processInfoForm').collect())
	}).done(function(data){
		if(data.code == "0"){
			BootstrapDialog.closeAll();
			customTimeOutDialog('信息提示','操作成功',null,2000,function(){
				redirectCall('/page/business/consultation/list?type=qcBefore');
			});
		}else{
			BootstrapDialog.closeAll();
			customAlertDialog(data.message, '错误提示', null, null);
		}
	});
}

//分诊通过
function doAssignOk(){
	//基础校验
	if (!$("#assignInfoForm").validationForm()) {
		return;
	}
	
	if(!$('#allot_hid').multipleSelect('getSelects')[0]){
		customAlertDialog("指定医院需填写", '错误提示', null, null);
		return;
	}
	
	if(!$('#allot_did').multipleSelect('getSelects')[0]){
		customAlertDialog("指定科室需填写", '错误提示', null, null);
		return;
	}
	
	if(!$('#allot_docid').multipleSelect('getSelects')[0]){
		customAlertDialog("指定医生需填写", '错误提示', null, null);
		return;
	}
	
	$.getApiClient('/consultation/assign/{conid}/done').setQuery({
		conid:conId
	}).put('#processInfoForm', function(params){
		return $.extend(params,collectAssignForm());
	}).done(function(data){
		if(data.code == "0"){
			customTimeOutDialog('信息提示','操作成功',null,2000,function(){
				redirectCall('/page/business/consultation/list?type=assign');
			});
		}else{
			customAlertDialog(data.message, '错误提示', null, null);
		}
	});
}

//分诊退回
function doAssignBack(){
	$.getApiClient('/consultation/assign/{conid}/back').setQuery({
		conid:conId
	}).put('#backInfoForm',function(params){
		return $.extend(params,$('#processInfoForm').collect())
	}).done(function(data){
		if(data.code == "0"){
			BootstrapDialog.closeAll();
			customTimeOutDialog('信息提示','操作成功',null,2000,function(){
				redirectCall('/page/business/consultation/list?type=assign');
			});
		}else{
			BootstrapDialog.closeAll();
			customAlertDialog(data.message, '错误提示', null, null);
		}
	});
}

//提交报告
function doReportOk(){
	//基础校验
	if (!$("#reportInfoForm").validationForm()) {
		customAlertDialog("请填写必填项目后提交", '提示', null, null);
		return;
	}
	$.getApiClient('/consultation/report/{conid}/done').setQuery({
		conid:conId
	}).put('#processInfoForm', function(params){
		return $.extend(params,collectReportForm());
	}).done(function(data){
		if(data.code == "0"){
			customTimeOutDialog('信息提示','操作成功',null,2000,function(){
				redirectCall('/page/business/consultation/list?type=myTask');
			});
		}else{
			customAlertDialog(data.message, '错误提示', null, null);
		}
	});
}

//报告退回
function doReportBack(){
	$.getApiClient('/consultation/report/{conid}/back').setQuery({
		conid:conId
	}).put('#backInfoForm',function(params){
		return $.extend(params,$('#processInfoForm').collect())
	}).done(function(data){
		if(data.code == "0"){
			BootstrapDialog.closeAll();
			customTimeOutDialog('信息提示','操作成功',null,2000,function(){
				redirectCall('/page/business/consultation/list?type=myTask');
			});
		}else{
			BootstrapDialog.closeAll();
			customAlertDialog(data.message, '错误提示', null, null);
		}
	});
}

//加入会议
function startConference(){
	var conferenceUrl = "startv2ex://" + videoConfig.confid   //confid  ：是视频会议id           
	+ "@slavemcu_1.machine1.v2c^^guest@"            //固定的参数串
	+ videoConfig.serviceip                                    //v2serviceip：视频服务器的ip
	+ "^guest^"                                    //固定的参数串
	+ loginUser.user_name                              // 在视频中显示的用户名称
	+ "^" + videoConfig.serviceip + "^"                      //v2serviceip：视频服务器的ip
	+ videoConfig.serviceip                                  //v2serviceip：视频服务器的ip 
	+ "^0^0^^^^";                                 //固定的参数串
	window.parent.open(conferenceUrl,"_blank");
}

//后质控通过
function doQcAfterOk(){
	$.getApiClient('/consultation/qcAfter/{conid}/done').setQuery({
		conid:conId
	}).put('#processInfoForm').done(function(data){
		if(data.code == "0"){
			customTimeOutDialog('信息提示','操作成功',null,2000,function(){
				redirectCall('/page/business/consultation/list?type=qcAfter');
			});
		}else{
			customAlertDialog(data.message, '错误提示', null, null);
		}
	});
}

//后质控退回
function doQcAfterBack(){
	$.getApiClient('/consultation/qcAfter/{conid}/back').setQuery({
		conid:conId
	}).put('#backInfoForm',function(params){
		return $.extend(params,$('#processInfoForm').collect())
	}).done(function(data){
		if(data.code == "0"){
			BootstrapDialog.closeAll();
			customTimeOutDialog('信息提示','操作成功',null,2000,function(){
				redirectCall('/page/business/consultation/list?type=qcAfter');
			});
		}else{
			BootstrapDialog.closeAll();
			customAlertDialog(data.message, '错误提示', null, null);
		}
	});
}

//转换字典码
function transItemCode(itemName,value){
	if(transItemCodeMap[itemName]){
		var text=transItemCodeMap[itemName][value];
		return text || value;
	}
	return value;
}